package com.cl.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.*;
import jakarta.servlet.http.HttpServletRequest;

import com.cl.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cl.annotation.IgnoreAuth;
import com.cl.annotation.SysLog;

import com.cl.entity.MerchantEntity;
import com.cl.entity.view.MerchantView;

import com.cl.service.MerchantService;
import com.cl.service.TokenService;
import com.cl.utils.PageUtils;
import com.cl.utils.R;
import com.cl.utils.EncryptUtil;
import com.cl.utils.MPUtil;
import com.cl.utils.MapUtils;
import com.cl.utils.CommonUtil;
import java.io.IOException;

/**
 * 商家
 * 后端接口
 * @author 
 * @email 
 * @date 2025-03-19 16:07:08
 */
@RestController
@RequestMapping("/merchant")
public class MerchantController {
    @Autowired
    private MerchantService merchantService;



	@Autowired
	private TokenService tokenService;
	
	/**
	 * 登录
	 */
	@IgnoreAuth
	@RequestMapping(value = "/login")
	public R login(String username, String password, String captcha, HttpServletRequest request) {
		MerchantEntity u = merchantService.getOne(new QueryWrapper<MerchantEntity>().eq("merchant_account", username));
        if(u==null || !u.getMerchantPassword().equals(EncryptUtil.md5(password))) {
            return R.error("账号或密码不正确");
        }
        if(!"是".equals(u.getSfsh())) return R.error("账号已锁定，请联系管理员审核。");
		String token = tokenService.generateToken(u.getId(), username,"merchant",  "merchant" );
		return R.ok().put("token", token);
	}



	/**
     * 注册
     */
	@IgnoreAuth
    @RequestMapping("/register")
    public R register(@RequestBody MerchantEntity merchant){
    	//ValidatorUtils.validateEntity(merchant);
        MerchantEntity u = merchantService.getOne(new QueryWrapper<MerchantEntity>().eq("merchant_account", merchant.getMerchantAccount()));
        if(u!=null) {
			return R.error("注册用户已存在");
		}
		Long uId = new Date().getTime();
		merchant.setId(uId);
        merchant.setMerchantPassword(EncryptUtil.md5(merchant.getMerchantPassword()));
        merchantService.save(merchant);
        return R.ok();
    }


	/**
	 * 退出
	 */
	@RequestMapping("/logout")
	public R logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return R.ok("退出成功");
	}

	/**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request){
    	Long id = (Long)request.getSession().getAttribute("userId");
        return R.ok().put("data", merchantService.selectView(new QueryWrapper<MerchantEntity>().eq("id", id)));
    }

    /**
     * 密码重置
     */
    @IgnoreAuth
	@RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request){
    	MerchantEntity u = merchantService.getOne(new QueryWrapper<MerchantEntity>().eq("merchant_account", username));
    	if(u==null) {
    		return R.error("账号不存在");
    	}
        u.setMerchantPassword(EncryptUtil.md5("123456"));
        merchantService.updateById(u);
        return R.ok("密码已重置为：123456");
    }




    /**
     * 后台列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,MerchantEntity merchant,
                                                                                                                                HttpServletRequest request){
                                    QueryWrapper<MerchantEntity> ew = new QueryWrapper<MerchantEntity>();
                                                                                                                                                                                                    
        
        
        PageUtils page = merchantService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, merchant), params), params));
        return R.ok().put("data", page);
    }







    /**
     * 前端列表
     */
	@IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,MerchantEntity merchant,
		HttpServletRequest request){
        QueryWrapper<MerchantEntity> ew = new QueryWrapper<MerchantEntity>();

		PageUtils page = merchantService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, merchant), params), params));
        return R.ok().put("data", page);
    }

	/**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( MerchantEntity merchant){
       	QueryWrapper<MerchantEntity> ew = new QueryWrapper<MerchantEntity>();
      	ew.allEq(MPUtil.allEQMapPre( merchant, "merchant"));
        return R.ok().put("data", merchantService.selectListView(ew));
    }

	 /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(MerchantEntity merchant){
        QueryWrapper< MerchantEntity> ew = new QueryWrapper< MerchantEntity>();
 		ew.allEq(MPUtil.allEQMapPre( merchant, "merchant"));
		MerchantView merchantView =  merchantService.selectView(ew);
		return R.ok("查询商家成功").put("data", merchantView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        MerchantEntity merchant = merchantService.getById(id);
		merchant = merchantService.selectView(new QueryWrapper<MerchantEntity>().eq("id", id));
        return R.ok().put("data", merchant);
    }

    /**
     * 前端详情
     */
	@IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        MerchantEntity merchant = merchantService.getById(id);
		merchant = merchantService.selectView(new QueryWrapper<MerchantEntity>().eq("id", id));
        return R.ok().put("data", merchant);
    }




    /**
     * 后端保存
     */
    @RequestMapping("/save")
    @SysLog("新增商家")
    public R save(@RequestBody MerchantEntity merchant, HttpServletRequest request){
        //验证字段唯一性，否则返回错误信息
        if(merchantService.count(new QueryWrapper<MerchantEntity>().eq("merchant_account", merchant.getMerchantAccount()))>0) {
            return R.error("商家账号已存在");
        }
        //ValidatorUtils.validateEntity(merchant);
        MerchantEntity u = merchantService.getOne(new QueryWrapper<MerchantEntity>().eq("merchant_account", merchant.getMerchantAccount()));
        if(u!=null) {
            return R.error("用户已存在");
        }
    	merchant.setId(new Date().getTime()+(long)Math.floor(Math.random()*1000));
		merchant.setId(new Date().getTime());
        merchant.setMerchantPassword(EncryptUtil.md5(merchant.getMerchantPassword()));
        merchantService.save(merchant);
        return R.ok().put("data",merchant.getId());
    }

    /**
     * 前端保存
     */
    @SysLog("新增商家")
    @RequestMapping("/add")
    public R add(@RequestBody MerchantEntity merchant, HttpServletRequest request){
        if(merchantService.count(new QueryWrapper<MerchantEntity>().eq("merchant_account", merchant.getMerchantAccount()))>0) {
            return R.error("商家账号已存在");
        }
    	merchant.setId(new Date().getTime()+(long)Math.floor(Math.random()*1000));
    	//ValidatorUtils.validateEntity(merchant);
        MerchantEntity u = merchantService.getOne(new QueryWrapper<MerchantEntity>().eq("merchant_account", merchant.getMerchantAccount()));
        if(u!=null) {
			return R.error("用户已存在");
		}
		merchant.setId(new Date().getTime());
        merchant.setMerchantPassword(EncryptUtil.md5(merchant.getMerchantPassword()));
        merchantService.save(merchant);
        return R.ok();
    }



    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    @SysLog("修改商家")
    public R update(@RequestBody MerchantEntity merchant, HttpServletRequest request){
        //ValidatorUtils.validateEntity(merchant);
        MerchantEntity merchantEntity = merchantService.getById(merchant.getId());
        if(StringUtils.isNotBlank(merchant.getMerchantPassword()) && !merchant.getMerchantPassword().equals(merchantEntity.getMerchantPassword())) {
            merchant.setMerchantPassword(EncryptUtil.md5(merchant.getMerchantPassword()));
        }
        merchantService.updateById(merchant);//全部更新
        return R.ok();
    }

    /**
     * 审核
     */
    @RequestMapping("/shBatch")
    @Transactional
    @SysLog("审核商家")
    public R update(@RequestBody Long[] ids, @RequestParam String sfsh, @RequestParam String shhf){
        List<MerchantEntity> list = new ArrayList<MerchantEntity>();
        for(Long id : ids) {
            MerchantEntity merchant = merchantService.getById(id);
            merchant.setSfsh(sfsh);
            merchant.setShhf(shhf);
            list.add(merchant);
        }
        merchantService.updateBatchById(list);
        return R.ok();
    }




    /**
     * 删除
     */
    @RequestMapping("/delete")
    @SysLog("删除商家")
    public R delete(@RequestBody Long[] ids){
        merchantService.removeBatchByIds(Arrays.asList(ids));
        return R.ok();
    }











}
